package com.txtsqlclient.ui.si;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.txtsqlclient.domain.DataSourceType;
import com.txtsqlclient.ui.Messages;
import com.txtsqlclient.ui.exception.SubInterfaceException;
import com.txtsqlclient.ui.helper.UserInputCapturer;
import com.txtsqlclient.ui.vo.Session;

/**
 * @author spadda
 * 
 */
public class DataSourceSubInterface extends PromptBasedSubInterface {

	private String dsTypeIdentifier;

	private final static Log LOGGER = LogFactory
			.getLog(DataSourceSubInterface.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.txtsqlclient.ui.InputGatherer#gatherInput(com.txtsqlclient.ui.Session)
	 */
	public void gatherInput(final Session session) throws SubInterfaceException {
		try {
			readDsType();
		} catch (IOException ie) {
			throw new SubInterfaceException(
					"Error while reading user input from console:", ie);
		}
		LOGGER.debug("Recieved user input for Data Source Type:"
				+ this.dsTypeIdentifier);
	}

	protected void readDsType() throws IOException {
		final StringBuffer dsTypePrompt = new StringBuffer(
				"Please enter the type of database (");
		for (final DataSourceType type : DataSourceType.getAllTypes()) {
			// The format of this string has not been moved inside DatabaseType
			// because this is purely for display purposes, which could change
			// tomorrow.
			dsTypePrompt.append(type.getIdentifier());
			dsTypePrompt.append('=');
			dsTypePrompt.append(type.getName());
			dsTypePrompt.append('/');
		}
		dsTypePrompt.replace(dsTypePrompt.length() - 1, dsTypePrompt.length(),
				"):");
		this.dsTypeIdentifier = UserInputCapturer.getLine(dsTypePrompt
				.toString());

		if (this.dsTypeIdentifier == null
				|| this.dsTypeIdentifier.trim().length() == 0) {
			System.out.println(Messages.DSTYPE_ERROR.toUpperCase());
			readDsType();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.txtsqlclient.ui.InputHandler#handleInput(com.txtsqlclient.ui.Session)
	 */
	public void handleInput(final Session session) throws SubInterfaceException {
		if (this.dsTypeIdentifier == null
				|| this.dsTypeIdentifier.trim().length() == 0) {
			throw new IllegalArgumentException(Messages.DSTYPE_ERROR);
		}

		final DataSourceType dsType = DataSourceType
				.resolveDataSourceType(this.dsTypeIdentifier);
		if (dsType == null) {
			throw new SubInterfaceException("The given Data Source type, \'"
					+ this.dsTypeIdentifier + "\' is invalid");
		} else {
			session.setDsType(dsType);

			SubInterface subHandler = getSubInterfaceFactory()
					.getDataSourceSubInterface(dsType);
			if (LOGGER.isTraceEnabled()) {
				LOGGER.trace("Obtained sub handler: " + subHandler.getClass()
						+ " based on the Data Source Type: " + dsType
						+ ". Proceeding with processing the sub handler");
			}
			subHandler.process(session);
		}
	}

}